<template>
  <div class="app-version-detail">
    <el-drawer
      v-loading="dataListLoading"
      :close-on-click-modal="false"
      :with-header="false"
      custom-class="detail"
      v-model="visible"
      size="44%"
      :title="$t('common.detail')"
      @close="cancel"
    >
      <div class="flex justify-end">
        <el-button @click="cancel" text class="w-8 m-2"
          ><svg-icon icon-class="Close"
        /></el-button>
      </div>
      <el-form
        ref="appVersionInfo"
        v-model="appVersionInfo"
        inline-message
        label-position="top"
        label-width="auto"
      >
        <el-descriptions direction="vertical" :column="12" border>
          <el-descriptions-item :label="$t('appstore.application.appIconUrl')" :span="4">
            <div style="text-align: center">
              <img
                style="height: 80px; width: 80px"
                :src="iconView(appVersionInfo.appIconUrl)"
              />
            </div>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('appstore.application.appName')" :span="4">
            {{ appVersionInfo.appName }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('appstore.application.appVersion')" :span="4">
            {{ appVersionInfo.appVersion }}
          </el-descriptions-item>
          <el-descriptions-item
            :label="$t('appstore.application.appVersionCode')"
            :span="4"
          >
            {{ appVersionInfo.appVersionCode }}
          </el-descriptions-item>
          <el-descriptions-item :label="$t('appstore.application.appSize')" :span="4">
            {{ appVersionInfo.appSize }} MB
          </el-descriptions-item>
          <el-descriptions-item :label="$t('developer_app.version_status')" :span="4">
            <!--            <el-tag>{{ handleStatus(appVersionInfo.status) }}</el-tag>-->
            <el-tag
              v-if="
                appVersionInfo.status === -1 ||
                appVersionInfo.status === 0 ||
                appVersionInfo.status === 2 ||
                appVersionInfo.status === 6
              "
              size="small"
              type="warning"
              >{{ handleStatus(appVersionInfo.status) }}</el-tag
            >
            <el-tag v-if="appVersionInfo.status === 1" size="small" type="success">{{
              handleStatus(appVersionInfo.status)
            }}</el-tag>
            <el-tag
              v-if="
                appVersionInfo.status === 5 ||
                appVersionInfo.status === 7 ||
                appVersionInfo.status === 9
              "
              size="small"
              type="private"
              >{{ handleStatus(appVersionInfo.status) }}</el-tag
            >
          </el-descriptions-item>
          <el-descriptions-item :label="$t('appstore.application.packageName')" :span="4">
            {{ appVersionInfo.packageName }}
          </el-descriptions-item>
          <!--          <el-descriptions-item :label="$t('appstore.application.downloadCount')" :span="4">-->
          <!--            {{ appVersionInfo.downloadCount }}-->
          <!--          </el-descriptions-item>-->
          <el-descriptions-item :label="$t('developer_app.u_key')" :span="4">
            {{ appVersionInfo.signUkey }}
          </el-descriptions-item>
          <el-descriptions-item
            :label="$t('appstore.application.support_device_type')"
            :span="4"
          >
            <el-tag
              v-if="appVersionInfo.landscape === 1"
              style="margin-left: 5px"
              size="small"
              >{{ $t("appstore.application.landscape") }}</el-tag
            >
            <el-tag
              v-if="appVersionInfo.portrait === 1"
              style="margin-left: 5px"
              size="small"
              >{{ $t("appstore.application.portrait") }}</el-tag
            >
          </el-descriptions-item>
          <el-descriptions-item
            :label="$t('appstore.application.developerName')"
            :span="4"
          >
            {{ appVersionInfo.developerName }}
          </el-descriptions-item>
          <el-descriptions-item
            :label="$t('appstore.application.release_area')"
            :span="8"
          >
            <el-tag v-for="area in appVersionInfo.releaseArea" :key="area" size="small">{{
              $t("country_or_region." + area)
            }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item
            :label="$t('appstore.application.mainLanguage')"
            :span="4"
          >
            <el-tag size="small">{{
              $t("language_list." + appVersionInfo.mainLanguage)
            }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item
            :label="$t('appstore.application.supportLanguage')"
            :span="8"
          >
            <div style="line-height: 2.4">
              <el-tag
                v-for="language in appVersionInfo.supportLanguage"
                :key="language"
                style="margin-left: 5px"
                size="small"
                >{{ $t("language_list." + language) }}</el-tag
              >
            </div>
          </el-descriptions-item>

          <el-descriptions-item :label="$t('appstore.application.submitTime')" :span="4">
            {{ formatDate(appVersionInfo.submitTime) }}
          </el-descriptions-item>

          <el-descriptions-item
            v-if="appVersionInfo.status !== 7"
            :label="$t('developer_app.initial_examine.examine_time')"
            :span="4"
          >
            {{ formatDate(appVersionInfo.initialExaminePassTime) }}
          </el-descriptions-item>
          <el-descriptions-item
            v-if="appVersionInfo.status !== 7 && appVersionInfo.status !== 8"
            :label="$t('developer_app.test_device')"
            :span="4"
          >
            <el-popover placement="right" width="500" trigger="click">
              <el-table :data="devModelData">
                <el-table-column
                  width="150"
                  prop="devModel"
                  :label="$t('developer_app.device_model')"
                  style="padding: 2px"
                />
                <el-table-column
                  width="150"
                  prop="testResult"
                  :label="$t('developer_app.status')"
                  style="padding: 2px"
                >
                  <template v-slot="scope">
                    <el-tag v-if="scope.row.testResult === 0" size="small" type="info">
                      {{ $t("developer_app.model_test_result[0].label") }}
                    </el-tag>
                    <el-tag v-if="scope.row.testResult === 1" size="small" type="success">
                      {{ $t("developer_app.model_test_result[1].label") }}
                    </el-tag>
                    <el-tag v-if="scope.row.testResult === 2" size="small" type="warning">
                      {{ $t("developer_app.model_test_result[2].label") }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column
                  width="350"
                  prop="remark"
                  :label="$t('developer_app.test_remark')"
                  style="padding: 2px"
                />
              </el-table>
              <template #reference>
                <el-button type="primary" size="small">{{
                  $t("developer_app.device_model")
                }}</el-button>
              </template>
            </el-popover>
          </el-descriptions-item>

          <el-descriptions-item :label="$t('developer_app.app_resource')" :span="12">
            <el-button type="primary" size="small" @click="viewImage">{{
              $t("developer_app.app_image")
            }}</el-button>
            <el-button type="primary" size="small" @click="viewPermission"
              >{{ $t("developer_app.app_permission") }}
            </el-button>
            <el-button
              v-if="appVersionInfo.status === 7 && isAuth('10400604.MANAGE')"
              type="primary"
              size="small"
              @click="handleInitialReview"
              >{{ $t("developer_app.initial_examine.examine") }}
            </el-button>
          </el-descriptions-item>
          <el-descriptions-item
            v-if="appVersionInfo.initialExamineExplain"
            :label="$t('developer_app.initial_examine.explanation')"
            :span="12"
          >
            {{ appVersionInfo.initialExamineExplain }}
          </el-descriptions-item>
          <el-descriptions-item
            v-if="appVersionInfo.signRejectedResultExplain"
            :label="$t('developer_app.sign.signature_rejection_reason')"
            :span="12"
          >
            {{ appVersionInfo.signRejectedResultExplain }}
          </el-descriptions-item>
          <el-descriptions-item
            v-if="appVersionInfo.apkDigest"
            :label="$t('developer_app.sign.app_summary')"
            :span="12"
          >
            {{ appVersionInfo.apkDigest }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 多语言 -->
        <div
          class="language-block"
          style="
            border: 1px solid #eeeeee;
            border-radius: 6px;
            margin-top: 16px;
            margin-bottom: 16px;
          "
        >
          <div
            v-for="(obj, index) in appVersionInfo.appLanguageInfos"
            :key="obj.language"
            class="text-gray-500 px-4 language-block__item"
          >
            <div
              class="flex justify-between items-center"
              role="button"
              @click="showLanguageInfo(index)"
            >
              <div style="padding: 16px 0">
                {{ $t("language_list." + obj.language) }}
              </div>
              <div class="flex flex-center">
                <i
                  class="el-icon-arrow-right mr-3 transition-all ml-5"
                  :class="{ 'transform rotate-90': obj.isActive }"
                />
              </div>
            </div>

            <el-descriptions
              v-if="obj.isActive"
              style="padding-bottom: 16px"
              :column="1"
              border
            >
              <el-descriptions-item label-style="width: 200px">
                <template #label>{{
                  $t("appstore.application.appIntroduction")
                }}</template>
                <div class="html-container">
                  <div style="padding: 12px" v-html="obj.introduction" />
                </div>
              </el-descriptions-item>
              <el-descriptions-item
                label-style="width: 200px"
                :label="$t('appstore.application.revision')"
              >
                <template #label>{{
                  $t("appstore.application.appIntroduction")
                }}</template>
                <div class="html-container">
                  <div style="padding: 12px" v-html="obj.revision" />
                </div>
              </el-descriptions-item>
              <el-descriptions-item
                v-if="landscapePicUrls.length || portraitPicUrls.length"
                label-style="width: 200px"
              >
                <template #label>{{ $t("appstore.application.screenshots") }}</template>
                <div>
                  <div style="text-align: center; padding: 8px">
                    <el-radio v-model="screenshotType" :label="1" :disabled="!landscape">
                      {{ $t("appstore.application.horizontalScreenshot") }}
                    </el-radio>
                    <el-radio v-model="screenshotType" :label="2" :disabled="!portrait">
                      {{ $t("appstore.application.verticalScreenshot") }}
                    </el-radio>
                  </div>
                  <el-carousel
                    v-if="screenshotType === 1"
                    :interval="4000"
                    type="card"
                    height="214px"
                  >
                    <el-carousel-item v-for="img in landscapePicUrls" :key="img.url">
                      <h3 class="medium">
                        <el-image
                          :src="baseApiUrl + img.url"
                          :preview-src-list="getImgList(landscapePicUrls)"
                        />
                      </h3>
                    </el-carousel-item>
                  </el-carousel>

                  <el-carousel
                    v-else-if="screenshotType === 2"
                    :interval="4000"
                    type="card"
                    height="380px"
                  >
                    <el-carousel-item v-for="img in portraitPicUrls" :key="img.url">
                      <h3 class="small">
                        <el-image
                          :src="baseApiUrl + img.url"
                          :preview-src-list="getImgList(portraitPicUrls)"
                        />
                      </h3>
                    </el-carousel-item>
                  </el-carousel>

                  <div v-else class="data-empty">
                    <icon-svg class="data-empty-icon" name="chart-data-empty" />
                    <div class="data-empty-text">{{ $t("common.noData") }}</div>
                  </div>
                </div>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </div>
      </el-form>
    </el-drawer>

    <view-res
      v-if="viewResVisible"
      ref="viewRes"
      @close="viewResVisible = false"
      @refreshDataList="getDataList"
    />
  </div>
</template>
<script>
import { getAppVersionInfo, screenshotList } from "@/api/developer-app";
import { formatDate } from "@/utils/formatDate";
import ViewRes from "./view-res";
import { HTMLDecode } from "@/utils";
import { getCountryList } from "@/api/user";
import { isAuth } from "@/utils";

var blockFun = function () {
  // 兼容处理
  var target = event.target || event.srcElement;
  // 判断是否匹配目标元素
  if (target.nodeName.toLocaleLowerCase() === "a") {
    console.log("当前点击的 a 标签: ", target);

    // 对捕获到的 a 标签进行处理，需要先禁止它的跳转行为
    if (event.preventDefault) {
      event.preventDefault();
    } else {
      window.event.returnValue = true;
    }

    // 处理完 a 标签的内容，重新触发跳转，根据原来 a 标签页 target 来判断是否需要新窗口打开

    var url = target.getAttribute("href");
    if (target.getAttribute("target") === "_blank") {
      window.goRoute(url);
    } else {
      window.location.href = url;
    }
  }
};

export default {
  components: {
    ViewRes,
  },
  data() {
    return {
      appLanguageInfos: [],
      baseApiUrl: import.meta.env.VITE_APP_BASE_API,
      portrait: false,
      portraitPicUrls: [],
      landscape: false,
      landscapePicUrls: [],
      visible: false,
      appVersionId: 0,
      appId: 0,
      appVersionInfo: "",
      dataListLoading: false,
      viewResVisible: false,
      screenshotType: 1,
      screenshots_h: [],
      screenshots_v: [],
      tempEnlargedPicture: [],
      devModelData: [],
      countries: [],
      langList: [
        { val: "zh_CN", label: this.$t("language_list.zh_CN") },
        { val: "en_US", label: this.$t("language_list.en_US") },
        { val: "ko", label: this.$t("language_list.ko") },
        { val: "jp", label: this.$t("language_list.jp") },
        { val: "pt", label: this.$t("language_list.pt") },
        { val: "ru", label: this.$t("language_list.ru") },
        { val: "fr", label: this.$t("language_list.fr") },
        { val: "de", label: this.$t("language_list.de") },
        { val: "es", label: this.$t("language_list.es") },
        { val: "it", label: this.$t("language_list.it") },
        { val: "ar", label: this.$t("language_list.ar") },
        { val: "other", label: this.$t("language_list.other") },
      ],
    };
  },
  mounted() {
    window.goRoute = this.goRoute;
    document.body.addEventListener("click", blockFun);
  },
  destroyed() {
    document.body.removeEventListener("click", blockFun);
  },
  methods: {
    getImgList(list) {
      const ret = [];
      for (const url of list) {
        ret.push(import.meta.env.VITE_APP_BASE_API + url.url);
      }
      return ret;
    },
    goRoute(url) {
      const encodeUri = encodeURIComponent(url);
      const routeUrl = this.$router.resolve({
        path: "/out-link",
        query: { target: encodeUri },
      });
      window.open(routeUrl.href, "_blank");
    },
    showLanguageInfo(index) {
      this.appVersionInfo.appLanguageInfos.map((item) => (item.isActive = false));
      this.landscapePicUrls = this.appVersionInfo.appLanguageInfos[
        index
      ].applicationScreenshotList.filter((v) => {
        return v.screenType === 1;
      });
      this.portraitPicUrls = this.appVersionInfo.appLanguageInfos[
        index
      ].applicationScreenshotList.filter((v) => {
        return v.screenType === 2;
      });
      this.appVersionInfo.appLanguageInfos[index].isActive = true;
    },
    getCountryList() {
      getCountryList()
        .then((data) => {
          this.countries = data;
        })
        .catch((e) => {
          this.$confirmError(e);
        });
    },
    countryFilter(areaCode) {
      let area = {};
      this.countries.forEach((item) => {
        if (item.countryCode3 === areaCode) {
          area = item;
        }
      });
      if (this.$i18n.locale === "en-US") {
        return area.countryNameEn;
      } else if (this.$i18n.locale === "zh-CN") {
        return area.countryNameZh;
      }
      return area.countryNameEn;
    },
    showEnlargedPicture(url) {
      url = this.iconView(url);
      this.tempEnlargedPicture.length = 0;
      this.tempEnlargedPicture.push(url);
    },
    handleStatus(status) {
      if (status === 9) {
        return this.$t("developer_app.version_status_option[0].label");
      } else if (status === 7) {
        return this.$t("developer_app.version_status_option[1].label");
      } else if (status === 6) {
        return this.$t("developer_app.version_status_option[2].label");
      } else if (status === 5) {
        return this.$t("developer_app.version_status_option[3].label");
      } else if (status === 2) {
        return this.$t("developer_app.version_status_option[4].label");
      } else if (status === 1) {
        return this.$t("developer_app.version_status_option[5].label");
      } else if (status === 0) {
        return this.$t("developer_app.version_status_option[6].label");
      } else if (status === -1) {
        return this.$t("developer_app.version_status_option[7].label");
      }
    },
    iconView(icon) {
      if (icon) {
        return import.meta.env.VITE_APP_BASE_API + icon;
        // return icon
      }
      // return require('@/assets/img/Android.png')
    },
    init(appId, appVersionId) {
      this.visible = true;
      this.appVersionId = appVersionId;
      this.appId = appId;
      this.dataListLoading = true;
      this.screenshots_h = [];
      this.screenshots_v = [];
      this.tempEnlargedPicture = [];
      if (this.appVersionId && this.appId) {
        this.getDataList();
      }
    },
    async getDataList() {
      this.getCountryList();
      getAppVersionInfo(this.appId, this.appVersionId)
        .then(async (data) => {
          this.appVersionInfo = data;
          this.devModelData = data.devModelList;
          this.appVersionInfo.appIntroduction = HTMLDecode(data.appIntroduction);
          this.appVersionInfo.revision = HTMLDecode(data.revision);
          // 将主语言置顶
          const index = this.appVersionInfo.supportLanguage.findIndex((v) => {
            return v === this.appVersionInfo.mainLanguage;
          });
          if (index > -1) {
            this.appVersionInfo.supportLanguage.splice(index, 1);
          }
          this.appVersionInfo.supportLanguage.splice(
            0,
            0,
            this.appVersionInfo.mainLanguage
          );

          this.landscape = data.landscape;
          this.portrait = data.portrait;
          if (data.portrait === 1) {
            this.portrait = true;
          }
          if (data.landscape === 1) {
            this.landscape = true;
          }
          if (this.landscape) {
            this.screenshotType = 1;
          } else if (this.portrait) {
            this.screenshotType = 2;
          }
          await screenshotList(this.appId, {
            appVersionId: this.appVersionId,
            screenType: 1,
          })
            .then((data) => {
              this.screenshots_h = data;
            })
            .catch((e) => {
              this.$confirmError(e);
              console.log(`err:${JSON.stringify(e)}`);
            });
          await screenshotList(this.appId, {
            appVersionId: this.appVersionId,
            screenType: 2,
          })
            .then((data) => {
              this.screenshots_v = data;
            })
            .catch((e) => {
              this.$confirmError(e);
              this.dataListLoading = false;
              console.log(`err:${JSON.stringify(e)}`);
            });
          this.appLanguageInfos = [];
          // 图片插入到一个列表中
          this.appVersionInfo.supportLanguage.forEach((l) => {
            let langObj = {
              language: l,
              introduction: "",
              applicationScreenshotList: [],
            };
            const himg = this.screenshots_h.find((s) => {
              return s.language === l;
            });
            if (himg) {
              langObj.introduction = himg.introduction;
              langObj.revision = himg.revision;
              langObj.applicationScreenshotList = langObj.applicationScreenshotList.concat(
                himg.applicationScreenshotList
              );
            }
            const vimg = this.screenshots_v.find((s) => {
              return s.language === l;
            });
            if (vimg) {
              langObj.applicationScreenshotList = langObj.applicationScreenshotList.concat(
                vimg.applicationScreenshotList
              );
            }
            this.appLanguageInfos.push(langObj);
            console.log(langObj);
          });
          this.appVersionInfo.appLanguageInfos = [];
          // 置顶主语言，并 active
          this.appLanguageInfos.forEach((v) => {
            v.applicationScreenshotList.forEach((img) => {
              img.url = img.url + "?t=" + new Date().getTime();
            });
            if (v.language === this.appVersionInfo.mainLanguage) {
              this.appVersionInfo.appLanguageInfos.splice(0, 0, {
                ...v,
                isActive: true,
              });
              this.landscapePicUrls = v.applicationScreenshotList.filter((img) => {
                return img.screenType === 1;
              });

              this.portraitPicUrls = v.applicationScreenshotList.filter((obj) => {
                return obj.screenType === 2;
              });
            } else {
              this.appVersionInfo.appLanguageInfos.push({
                ...v,
                isActive: false,
              });
            }
          });

          this.dataListLoading = false;
        })
        .catch((e) => {
          this.dataListLoading = false;
          this.$confirmError(e);
          console.log(`err:${JSON.stringify(e)}`);
        });
    },
    cancel() {
      this.visible = false;
      this.$emit("close");
      this.$emit("refreshDataList");
    },
    formatDate(cellValue) {
      return formatDate(cellValue, "YYYY-MM-DD HH:mm:ss");
    },
    viewImage() {
      this.viewResVisible = true;
      this.$nextTick(() => {
        this.$refs.viewRes.init(this.appVersionId, "image");
      });
    },
    viewPermission() {
      this.viewResVisible = true;
      this.$nextTick(() => {
        this.$refs.viewRes.init(this.appVersionId, "permission");
      });
    },
    handleInitialReview() {
      this.viewResVisible = true;
      this.$nextTick(() => {
        this.$refs.viewRes.init(this.appVersionId, "initialReview");
      });
    },
    isAuth,
  },
};
</script>

<style lang="scss" scoped>
.html-container {
  ::v-deep a {
    color: #3f9eff;
    text-decoration: underline;
  }
  ::v-deep blockquote {
    border-left: solid 4px #eeeeee;
    padding-left: 16px;
  }
  ::v-deep h1,
  h2,
  h3,
  h4,
  h5,
  h6 {
    font-weight: 600;
  }

  ::v-deep h1 {
    font-size: 40px;
  }

  ::v-deep h2 {
    font-size: 32px;
  }

  ::v-deep h3 {
    font-size: 28px;
  }

  ::v-deep h4 {
    font-size: 24px;
  }
  ::v-deep h5 {
    font-size: 20px;
  }
  ::v-deep h6 {
    font-size: 16px;
  }
}

.language-block__item {
  border-top: 1px solid #eeeeee;
}

.language-block__item:first-child {
  border-top: none;
}
</style>

<style lang="scss">
.app-version-detail {
  .el-popover {
    width: 35%;
    overflow: auto;
    height: 304px;
  }

  .el-select {
    width: 100%;
  }

  .el-input.is-disabled .el-input__inner {
    background-color: white;
    color: black;
  }

  .timeDiv {
    width: 100%;
  }

  .el-col {
    text-align: center;
    border: 1px solid #ddd;
  }

  .table {
    .el-col {
      text-align: center;
      border: 1px solid #ddd;
      padding: 5px;
    }
  }

  .table-head {
    background: #eee;
  }
}
</style>
